//
//  TabBarController.swift
//  SwiftWB
//
//  Created by luozhijun on 16/8/29.
//  Copyright © 2016年 luozhijun. All rights reserved.
//

import UIKit

class TabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 代码创建子控制器
//        createChildVcFromJSONFile()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        setupTabItems()
    }
}

#if false
// Tag 决定用stroyboard添加子控制器，所以注释
//MARK: - 添加子控制器
extension TabBarController {
    func createChildVcFromJSONFile() {
        // 从json文件中获取子控制器信息
        guard let path = NSBundle.mainBundle().pathForResource("MainVCSettings", ofType: "json") else {
            ColorLog.warn("未找到描述子控制器信息的json文件")
            return
        }
        guard let jsonData = NSData(contentsOfFile: path) else {
            ColorLog.warn("获取数据失败")
            return
        }
        guard let temp = try? NSJSONSerialization.JSONObjectWithData(jsonData, options: .AllowFragments) as? [[String: AnyObject]] else {
            return
        }
        guard let jsonObject = temp else {
            return
        }
        
        // 创建所有子控制器
        for i in 0..<jsonObject.count {
            let item = jsonObject[i]
            guard let vcName = item["vcName"] as? String else {
                continue
            }
            addChildViewController(vcName, title: item["title"] as? String, imageName: item["imageName"] as? String)
            
            if i == 1 { // 预留一个位置用来存放加号按钮
                addChildViewController(UIViewController())
            }
        }
    }
    
    func addChildViewController(childVcName: String, title: String?, imageName: String?) {
        // swift中，类名必须带有命名空间，而此处获取到的childVcClass不带有命名空间
        // 自己写的代码的命名空间默认是工程名
        let nameSpace = NSBundle.mainBundle().infoDictionary![kCFBundleExecutableKey as String] as! String
        let childVcClassName = nameSpace + "." + childVcName
        
        guard let childVcClass = NSClassFromString(childVcClassName) as? UIViewController.Type else {
            debugLog("获取子控制器类型失败")
            return
        }
        
        let childVc = childVcClass.init()
        childVc.title = title
        if let imageName = imageName {
            childVc.tabBarItem.image = UIImage(named: imageName)
            childVc.tabBarItem.selectedImage = UIImage(named: imageName + highlightImageNameSuffix)
        }
        let navi = UINavigationController(rootViewController: childVc)
        addChildViewController(navi)
    }
}
#endif

//MARK: - 设置tabItem，添加中间的加号按钮
extension TabBarController {
    // swift 2.x中, private 是对当前文件可见
    private func setupTabItems() {
        for i in 0..<tabBar.items!.count {
            let tabItem = tabBar.items![i]
            if i == 2 {
                // 令中间的item不可点击, 以下面添加的按钮代替之
                // 也可在storyboard中设置, 便可少写这层for循环的代码
                tabItem.enabled = false
            }
        }
        
        // 添加中间的加号按钮
        let composeButton = UIButton(imageName: "tabbar_compose_icon_add", bgImageName: "tabbar_compose_button")
        composeButton.center = CGPointMake(tabBar.center.x, tabBar.frame.size.height * 0.5)
        tabBar.addSubview(composeButton)
        // swift中selector的写法
        // 1.Selector("method name")
        // 2.#selector(method name) 推荐
        // target-selector 模式是objc特性, 可看看这篇文章:http://stackoverflow.com/questions/24007650/selector-in-swift
        composeButton.addTarget(self, action: #selector(composeButtonClicked), forControlEvents: .TouchUpInside)
    }
}

//MARK: - Handle Events
extension TabBarController {
    // 事件监听依赖于消息发送, 而消息机制是objc的特性,
    // 在swift中, 如果在一个有private标识, 那么可认为它是纯swift方法, 将不会有objc的特性,
    // 所以发现下面加了private之后, 点击对应按钮将奔溃, 提示无法找到selector;
    // 原因是private类型的方法不会加入到objc的方法列表中, 也即无法通过我们给定的slector找到这个方法, 所以报unreconized selector错误,
    // 如果addTarget时, 用到是#selector(), 发现无法编译通过,
    // 提示:Argument of '#selector' refers to a method that is not exposed to Objective-C,
    // 而Selector("")只会报警告: No method declared with Objective-C selector 'composeButtonClicked',
    // 所以推荐使用#selector, 能在运行之前检测;
    // objc中: 将方法包装成SEL-->Class结构体中查找方法列表-->根据SEL找到imp指针(函数指针)-->执行函数代码
    // 如果既要保留objc机制, 又要实现访问控制, 解决办法是在private前面加上@objc
    @objc private func composeButtonClicked() {
        ColorLog.eventTriggered()
    }
}
